<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="区县信息" data-page-identification="b_0447fcdjcw">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_r2bed6ie5v 面包屑_x4r2b812i6 -->
            <a-breadcrumb class="vid_r2bed6ie5v" style="word-break: break-word">
                <a-breadcrumb-item
                    v-for="(item, index) in vid_r2bed6ie5v_props_tabConfig"
                    :key="index"
                    @click="handleBreadcrumbJump(router, item)"
                    href=""
                >
                    <template v-if="vid_r2bed6ie5v_props.rt_showIcon">
                        <span v-if="/^(https?:|mailto:|tel:|data:image)/.test(item.icon)" role="img" class="anticon"
                            ><embed style="width: 1em; height: 1em" :src="item.icon"
                        /></span>
                        <component v-else :is="item.icon" />
                    </template>
                    {{ item.title }}
                </a-breadcrumb-item>
            </a-breadcrumb>
            <!-- end vid_r2bed6ie5v 面包屑_x4r2b812i6 -->
            <!-- begin vid_kl5sk1b1bg 自定义模板_swbmjmrp4a -->
            <!--            新建区域-->
            <a-modal
                :visible="state.addOrEditVisible"
                :title="state.modalTitle"
                @ok="handleSubmit"
                @cancel="handleCancel"
                centered
                destroy-on-close
                :ok-button-props="{ loading: state.okBtnLoading }"
            >
                <div class="my-page">
                    <a-form :model="state.formModel" ref="formRef">
                        <a-row>
                            <a-col :span="24">
                                <a-form-item
                                    label="目录名称"
                                    :rules="[{ required: true, message: '请输入目录名称！' }]"
                                    name="name"
                                >
                                    <a-input v-model:value="state.formModel.name" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item
                                    label="区域编码"
                                    :rules="[{ required: true, message: '请输入区域编码！' }]"
                                    name="name"
                                >
                                    <a-input v-model:value="state.formModel.code" />
                                </a-form-item>
                            </a-col>
                        </a-row>

                        <a-col :span="24">
                            <a-form-item
                                label="目录类型"
                                :rules="[{ required: true, message: '请选择目录类型！' }]"
                                name="type"
                            >
                                <a-select
                                    show-search
                                    :options="[
                                        { label: '省', value: '省' },
                                        { label: '市', value: '市' }
                                    ]"
                                    v-model:value="state.formModel.type"
                                    placeholder="请选择目录类型"
                                    @change="state.formModel.parentId = undefined"
                                />
                            </a-form-item>
                        </a-col>
                        <a-row v-if="state.formModel.type === '市'">
                            <a-col :span="24">
                                <a-form-item
                                    label="父级目录"
                                    :rules="[{ required: true, message: '请选择目录名称！' }]"
                                    name="parentId"
                                >
                                    <a-select
                                        show-search
                                        :options="state.provinceList"
                                        :field-names="{ label: 'name', value: 'id' }"
                                        :filterOption="
                                            (input, option) => {
                                                return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }
                                        "
                                        v-model:value="state.formModel.parentId"
                                        placeholder="请选择目录类型"
                                        @focus="getProvinceList"
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-col :span="24">
                            <a-form-item
                                label="经度"
                                :rules="[{ required: true, message: '请输入经度！' }]"
                                name="longitude"
                            >
                                <a-input v-model:value="state.formModel.longitude" placeholder="请输入经度" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item
                                label="纬度"
                                :rules="[{ required: true, message: '请输入纬度！' }]"
                                name="latitude"
                            >
                                <a-input v-model:value="state.formModel.latitude" placeholder="请输入纬度" />
                            </a-form-item>
                        </a-col>
                    </a-form>
                </div>
            </a-modal>
            <!--            新建区域-->
            <!--            新建区县-->
            <a-modal
                :visible="state.addOrEditCountryVisible"
                :title="state.countryModalTitle"
                @ok="handleSubmitCountry"
                @cancel="handleCancel"
                centered
                destroy-on-close
                :ok-button-props="{ loading: state.okBtnLoading }"
            >
                <div class="my-page">
                    <a-form :model="state.countryFormModel" ref="countryFormRef">
                        <a-row>
                            <a-col :span="24">
                                <a-form-item
                                    label="区县名称"
                                    :rules="[{ required: true, message: '请输入区县名称！' }]"
                                    name="areaName"
                                >
                                    <a-input v-model:value="state.countryFormModel.areaName" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item
                                    label="区县编码"
                                    :rules="[{ required: true, message: '请输入code！' }]"
                                    name="code"
                                >
                                    <a-input v-model:value="state.countryFormModel.code" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row>
                            <a-col :span="24">
                                <a-form-item
                                    label="父级目录"
                                    :rules="[{ required: true, message: '请选择父级目录！' }]"
                                    name="regionId"
                                >
                                    <a-tree-select
                                        v-model:value="state.countryFormModel.regionId"
                                        show-search
                                        style="width: 100%"
                                        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                                        placeholder="请选择父级目录"
                                        allow-clear
                                        tree-default-expand-all
                                        :tree-data="state.countryTreeList"
                                        tree-node-filter-prop="label"
                                        :field-names="{
                                            children: 'children',
                                            label: 'name',
                                            value: 'id'
                                        }"
                                        @focus="getCountryTreeList"
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row>
                            <a-col :span="24">
                                <a-form-item label="位置信息">
                                    <a-textarea
                                        v-model:value="state.countryFormModel.locationInfo"
                                        placeholder="请输入位置信息"
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-col :span="24">
                            <a-form-item
                                label="经度"
                                :rules="[{ required: true, message: '请输入经度！' }]"
                                name="longitude"
                            >
                                <a-input v-model:value="state.countryFormModel.longitude" placeholder="请输入经度" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item
                                label="纬度"
                                :rules="[{ required: true, message: '请输入纬度！' }]"
                                name="latitude"
                            >
                                <a-input v-model:value="state.countryFormModel.latitude" placeholder="请输入纬度" />
                            </a-form-item>
                        </a-col>
                    </a-form>
                </div>
            </a-modal>
            <!--            新建区县-->
            <div class="body">
                <a-row>
                    <a-col :span="4">
                        <div class="left-tree">
                            <al-box class="search">
                                <a-row>
                                    <a-col :span="21">
                                        <a-input
                                            autocomplete="off"
                                            v-model:value="state.searchName"
                                            placeholder="请输入"
                                            :allowClear="true"
                                            @change="getTreeData"
                                        >
                                            <template #suffix>
                                                <search-outlined />
                                            </template>
                                        </a-input>
                                    </a-col>
                                    <a-col
                                        :span="3"
                                        style="display: flex; justify-content: flex-end; align-items: center"
                                    >
                                        <!--                                        <PlusSquareFilled  />-->
                                        <CloseCircleFilled
                                            style="font-size: 20px; transform: rotate(45deg)"
                                            @click="handleAddMenu"
                                        />
                                    </a-col>
                                </a-row>
                            </al-box>
                            <div class="tree-continer">
                                <a-tree
                                    v-model:checkedKeys="state.treeProps.checkedKeys"
                                    v-model:selectedKeys="state.treeProps.selectedKeys"
                                    v-model:expandedKeys="state.treeProps.expandedKeys"
                                    :fieldNames="{ children: 'children', title: 'name', key: 'id' }"
                                    :selectedBackgroundColor="'#EBF1FF'"
                                    :backgroundColor="'#F5F5F5'"
                                    :tree-data="state.treeData"
                                    @select="onSelect"
                                >
                                    <template #title="{ name, id }" class="btn-show">
                                        <div class="tree-btns">
                                            <span>{{ name }}</span>
                                            <div
                                                style="display: inline-block; margin: 0 5px"
                                                @click.stop="handleEditTree(id)"
                                            >
                                                <a-tooltip>
                                                    <template #title>编辑</template>
                                                    <EditOutlined class="svg-icon" @click.stop="handleEditTree(id)" />
                                                </a-tooltip>
                                            </div>
                                            <a-popconfirm @confirm.stop="handleDeleteTree(id)" title="确定删除吗？">
                                                <div none style="display: inline-block">
                                                    <DeleteOutlined class="svg-icon" />
                                                </div>
                                            </a-popconfirm>
                                        </div>
                                    </template>
                                </a-tree>
                            </div>
                        </div>
                    </a-col>
                    <a-col :span="20">
                        <div class="right-content">
                            <a-row :gutter="24">
                                <a-col :span="5">
                                    <a-form-item label="区县" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
                                        <a-input v-model:value="state.areaName" />
                                    </a-form-item>
                                </a-col>
                                <a-col>
                                    <a-space>
                                        <a-button
                                            type="primary"
                                            @click="getData('search', state.treeProps.selectedKeys)"
                                            >查询</a-button
                                        >
                                        <a-button type="primary" @click="getData('reset', state.treeProps.selectedKeys)"
                                            >重置</a-button
                                        >
                                    </a-space>
                                </a-col>
                            </a-row>
                            <div class="content-title">
                                <div class="tip">
                                    <div class="tip-msg">区县信息</div>
                                </div>
                                <div class="button-group">
                                    <a-space>
                                        <a-button type="primary" @click="handleAddDistrictAndCounty">新建</a-button>
                                        <a-upload
                                            :before-upload="handleImport"
                                            :file-list="[]"
                                            accept=".xlsx, image/*, .docx, .rp, .xls"
                                        >
                                            <a-button type="primary" ghost>导入</a-button>
                                        </a-upload>
                                        <a-button type="primary" ghost @click="handleDownLoadTemplate"
                                            >下载模板</a-button
                                        >
                                        <!--<a-button type="primary" ghost @click="handleExport">导出</a-button> -->
                                    </a-space>
                                </div>
                            </div>
                            <div class="default-table">
                                <a-table
                                    :scroll="{ x: 'max-content' }"
                                    :columns="columns"
                                    :data-source="state.dataSource"
                                    bordered
                                    :loading="state.spinng"
                                    :pagination="pagination"
                                    @change="handleTableChange"
                                >
                                    <template #bodyCell="{ column, record, text }">
                                        <template v-if="column.dataIndex === 'opration'">
                                            <a-space>
                                                <a-button type="link" @click="handleEditCountry(record)">编辑</a-button>
                                                <a-popconfirm
                                                    @confirm="handleDeleteCountry(record)"
                                                    title="确定删除吗？"
                                                >
                                                    <a-button type="link">删除</a-button>
                                                </a-popconfirm>
                                            </a-space>
                                        </template>
                                    </template>
                                </a-table>
                            </div>
                        </div>
                    </a-col>
                </a-row>
            </div>
            <!-- end vid_kl5sk1b1bg 自定义模板_swbmjmrp4a -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    const vid_r2bed6ie5v_props = reactive({
        rt_showIcon: false
    })

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */
    const vid_r2bed6ie5v_props_tabConfig = computed(() => {
        const initValue = [
            {
                'key': 'tab1',
                'title': '基础信息',
                'targetPage': { 'settingType': '', 'url': '', 'customUrl': '' },
                'icon': '',
                'parameter': [],
                'applicationId': 3000000036,
                'query': {}
            },
            {
                'key': 'tab2',
                'title': '区县信息',
                'icon': '',
                'targetPage': { 'settingType': '', 'url': '', 'customUrl': '' },
                'parameter': [],
                'applicationId': 3000000036,
                'query': {}
            }
        ]
        return initValue
    })
    /*** PUBLISH_EXEGESIS ***
 systemStore.addBreadcrumbInfo(vid_r2bed6ie5v_props_tabConfig.value);
 *** PUBLISH_EXEGESIS ***/
    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    onMounted(() => {
        getTreeData()
    })
    const state = reactive({
        areaName: '',
        searchName: '',
        addOrEditVisible: false,
        addOrEditCountryVisible: false,
        modalTitle: '',
        countryModalTitle: '',
        formModel: {
            name: undefined,
            code: undefined,
            type: '省',
            parentId: 0,
            longitude: undefined,
            latitude: undefined
        },
        countryFormModel: {
            areaName: undefined,
            locationInfo: undefined,
            regionId: undefined,
            longitude: undefined,
            latitude: undefined,
            code: undefined
        },
        provinceList: [],
        treeData: [],
        treeProps: {
            lazyParams: undefined,
            selected: { singleValue: '', title: [], value: [], option: [], singleLabel: '' },
            clickNode: { nodeTitle: '', nodeKey: '', nodeParentKey: '' },
            checkedKeys: [],
            selectedKeys: [],
            expandedKeys: [],
            treeData: []
        },
        dataSource: [],
        deleteVisible: false,
        changeVisible: false,
        changeRecord: [],
        okBtnLoading: false,
        spinng: false,
        countryTreeList: []
    })
    const pagination = ref({
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showTotal: (total, range) =>
            `共 ${total} 条 第 ${pagination.value.current}/${Math.ceil(
                pagination.value.total / pagination.value.pageSize
            )} 页`,
        showQuickJumper: true // 显示快捷跳转
    })
    const currentTree = ref({})
    const currentData = ref({})
    const activeKey = ref('1')
    const columns = [
        {
            title: '区县名称',
            align: 'center',
            dataIndex: 'areaName'
        },
        {
            title: '区县编码',
            align: 'center',
            dataIndex: 'code'
        },
        {
            title: '经度',
            align: 'center',
            dataIndex: 'longitude'
        },
        {
            title: '纬度',
            align: 'center',
            dataIndex: 'latitude'
        },
        {
            title: '位置信息',
            align: 'center',
            dataIndex: 'locationInfo'
        },
        {
            title: '更新人',
            align: 'center',
            dataIndex: 'lastModifyByName'
        },
        {
            title: '更新时间',
            align: 'center',
            dataIndex: 'lastModifyDate'
        },
        {
            title: '操作',
            align: 'center',
            width: 150,
            fixed: 'right',
            dataIndex: 'opration'
        }
    ]
    // 获取树

    // 获取区县数据
    function getData(flag, id) {
        state.spinng = true
        if (flag === 'reset') {
            state.areaName = ''
        }
        if (flag === 'reset' || flag === 'search') {
            pagination.value.current = 1
            pagination.value.pageSize = 10
        }
        const params = {
            'filter': {
                areaName: state.areaName,
                regionId: id
            },
            'pageNo': pagination.value.current,
            'pageSize': pagination.value.pageSize
        }
        post(`/dynamic-price/api/v1/area_info/search`, params)
            .then(data => {
                if (data.status !== 'success') {
                    message.error(data.errorMsg)
                    return
                }
                state.dataSource = data.data.content
                pagination.value.total = data.data.totalElements
            })
            .finally(() => {
                currentData.value = {}
                currentTree.value = {}
                state.spinng = false
            })
    }
    // 当分页变化时，触发获取数据
    const handleTableChange = ({ current, pageSize, total }) => {
        pagination.value.current = current
        pagination.value.pageSize = pageSize
        getData('table', state.treeProps.selectedKeys)
    }
    // 获取所有子节点的 ID
    const getAllChildKeys = node => {
        const keys = [node.id]
        if (node.children && node.children.length) {
            node.children.forEach(child => {
                keys.push(...getAllChildKeys(child))
            })
        }
        return keys
    }

    const onSelect = (selectedKeys, { selected, node }) => {
        const allKeys = getAllChildKeys(node)

        if (selected) {
            state.treeProps.selectedKeys = [...new Set([...state.treeProps.selectedKeys, ...allKeys])]
            pagination.value.current = 1
            pagination.value.pageSize = 10
            getData('search', state.treeProps.selectedKeys)
        } else {
            state.treeProps.selectedKeys = state.treeProps.selectedKeys.filter(key => !allKeys.includes(key))
        }
    }
    //     新建树区域
    function handleAddMenu() {
        state.addOrEditVisible = true
        state.modalTitle = '新建'
    }

    //     导入
    function handleImport(file) {
        const data = new FormData()
        data.append('file', file)
        post(`/dynamic-price/api/v1/data/import/area_info`, data).then(data => {
            if (data.status !== 'success') {
                message.error(data.errorMsg)
                return
            }
            message.success('导入成功')
            // 成功后刷新列表
            getData('search', state.treeProps.selectedKeys)
        })
    }
    //     下载模板
    function handleDownLoadTemplate() {
        function downloadExcel(response, name) {
            const blob = new Blob([response], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
            })
            const downloadElement = document.createElement('a')
            const href = window.URL.createObjectURL(blob) // 创建下载的链接
            downloadElement.href = href
            downloadElement.download = name // 下载后文件名
            document.body.appendChild(downloadElement)
            downloadElement.click() // 点击下载
            document.body.removeChild(downloadElement) // 下载完成移除元素
            window.URL.revokeObjectURL(href)
            return href
        }

        get(`/dynamic-price/api/v1/template/download/area_info`, null, {
            responseType: 'arraybuffer'
        }).then(data => {
            downloadExcel(data, '区县信息.xlsx')
        })
    }
    //     导出
    function handleExport() {}
    // 新建区县
    function handleAddDistrictAndCounty() {
        state.addOrEditCountryVisible = true
        state.countryModalTitle = '新建区县'
    }
    //     编辑
    function handleEditCountry(record) {
        getCountryTreeList()
        currentData.value = record
        state.countryModalTitle = '编辑区县'
        state.countryFormModel = cloneDeep(record)
        state.addOrEditCountryVisible = true
    }
    //     删除
    function handleDeleteCountry(record) {
        del(`/dynamic-price/api/v1/area_info/${record.id}`).then(data => {
            if (data.status !== 'success') {
                message.error(data.errorMsg)
                return
            }
            message.success('删除成功')
            getData('table', state.treeProps.selectedKeys)
        })
    }
    //     编辑
    function handleEditTree(id) {
        get(`/dynamic-price/api/v1/region_info/${id}`).then(data => {
            if (data.status !== 'success') {
                message.error(data.errorMsg)
                return
            }
            getProvinceList()
            currentTree.value.id = id
            state.formModel = data.data
            state.addOrEditVisible = true
            state.modalTitle = '编辑'
        })
    }
    //     删除
    function handleDeleteTree(id) {
        del(`/dynamic-price/api/v1/region_info/${id}`).then(data => {
            if (data.status !== 'success') {
                message.error(data.errorMsg)
                return
            }
            message.success('删除成功')
            getTreeData()
        })
    }
    const countryFormRef = ref(null)
    const formRef = ref(null)
    //     保存区域
    function handleSubmit() {
        formRef.value.validate().then(() => {
            const params = state.formModel
            if (!params.parentId) {
                params.parentId = 0
            }
            if (currentTree.value.id) {
                put(`/dynamic-price/api/v1/region_info/${currentTree.value.id}`, params)
                    .then(data => {
                        if (data.status !== 'success') {
                            message.error(data.errorMsg)
                            return
                        }
                        message.success('修改成功')
                        handleCancel()
                        getTreeData(true)
                    })
                    .finally(() => {
                        state.okBtnLoading = false
                    })
            } else {
                post('/dynamic-price/api/v1/region_info', params)
                    .then(data => {
                        if (data.status !== 'success') {
                            message.error(data.errorMsg)
                            return
                        }
                        message.success('添加成功')
                        handleCancel()
                        getTreeData()
                    })
                    .finally(() => {
                        state.okBtnLoading = false
                    })
            }
        })
    }
    // 保存区县
    function handleSubmitCountry() {
        countryFormRef.value.validate().then(() => {
            state.okBtnLoading = true
            if (currentData.value.id) {
                put(`/dynamic-price/api/v1/area_info/${currentData.value.id}`, state.countryFormModel)
                    .then(data => {
                        if (data.status !== 'success') {
                            message.error(data.errorMsg)
                            return
                        }
                        message.success('修改成功')
                        handleCancel()
                        getData('table', state.treeProps.selectedKeys)
                    })
                    .finally(() => {
                        state.okBtnLoading = false
                    })
            } else {
                post('/dynamic-price/api/v1/area_info', state.countryFormModel)
                    .then(data => {
                        if (data.status !== 'success') {
                            message.error(data.errorMsg)
                            return
                        }
                        message.success('添加成功')
                        handleCancel()
                        getData('search', state.treeProps.selectedKeys)
                    })
                    .finally(() => {
                        state.okBtnLoading = false
                    })
            }
        })
    }
    // 获取树列表
    function getTreeData(flag) {
        post(`/dynamic-price/api/v1/region_info/tree`, {
            'name': state.searchName
        }).then(res => {
            if (res.status !== 'success') {
                message.error(res.errorMsg)
                return
            }
            state.treeData = res.data
            if (!flag && state.treeData.length > 0) {
                // 获取第一个节点及其所有子节点的 ID
                const firstNode = state.treeData[0]
                const allKeys = getAllChildKeys(firstNode)

                // 设置 selectedKeys 和 expandedKeys
                state.treeProps.selectedKeys = allKeys
                state.treeProps.expandedKeys = [firstNode.id] // 展开第一个节点
                // 如果需要立即加载数据，可以在此调用 getData
                getData('search', allKeys)
            }
        })
    }
    function getCountryTreeList() {
        get('/dynamic-price/api/v1/region_info/select_tree').then(data => {
            if (data.status !== 'success') {
                message.error(data.errorMsg)
                return
            }
            state.countryTreeList = data.data
        })
    }
    // watch(
    //     () => state.treeData,
    //     list => {
    //         if (!list.length) {
    //             return
    //         }
    //
    //     },
    //     { deep: true, immediate: true }
    // )
    // 获取省份
    function getProvinceList() {
        get(`/dynamic-price/api/v1/region_info/search/省`).then(data => {
            if (data.status !== 'success') {
                message.error(data.errorMsg)
                return
            }
            state.provinceList = data.data
        })
    }

    function handleCancel() {
        state.formModel = {
            name: undefined,
            code: undefined,
            type: '省',
            parentId: 0,
            longitude: undefined,
            latitude: undefined
        }
        state.countryFormModel = {
            areaName: undefined,
            locationInfo: undefined,
            regionId: undefined,
            longitude: undefined,
            latitude: undefined,
            code: undefined
        }
        state.addOrEditCountryVisible = false
        state.addOrEditVisible = false
        currentTree.value = {}
        currentData.value = {}
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    .vid_r2bed6ie5v :deep(a) {
        color: undefined;
    }
    :deep(.vid_r2bed6ie5v.@{ant-prefix}-breadcrumb) > span:last-child a {
        color: undefined;
        opacity: 0.75;
    }
    .vid_r2bed6ie5v {
        height: 40px;
        display: flex;
        align-items: center;
        flex-wrap: undefined;
        margin-bottom: 24px;
        padding-right: 24px;
        padding-left: 24px;
        background-color: #ffffff;
    }

    /*样式*/
    .body {
        padding: 0 24px;
    }
    .left-tree {
        background-color: #fff;
        height: 100%;
        padding: 16px;
        margin-right: 16px;
        height: calc(100vh - 150px);
    }
    .tree-continer {
        height: calc(100vh - 250px);
        overflow: auto;
    }
    .right-content {
        height: calc(100vh - 150px);
        padding: 16px;
        overflow: auto;
        background-color: #fff;
    }
    .page_root {
        width: 100%;
        height: 100%;
        overflow: hidden;
    }
    .top-search {
        height: 80px;
        background-color: #fff;
        padding: 16px 24px;
        border-radius: 4px;
        margin-bottom: 16px;
    }
    .content {
        background-color: #fff;
        border-radius: 4px;
        padding: 24px;
        padding-top: 0;
        height: calc(100vh - 220px);
        overflow: auto;
        padding-bottom: 8px;
    }
    /*表格按钮通用样式*/
    .default-table :deep(.@{ant-prefix}-table-thead) > tr > th {
        background: #f5f5f5;
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 600;
        color: #262626;
        padding: 8px 16px;
    }
    .default-table :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 400;
        color: #595959;
        border-bottom: 1px solid #d9d9d9;
        padding: 6px 16px;
        word-break: break-all;
    }
    /*表格按钮通用样式*/
    /*表格顶部的标题*/
    .content-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16px;
    }
    .tip {
        display: flex;
        align-items: center;
    }
    .tip-msg {
        height: 20px;
        border-left: 4px solid #d7000f;
        font-size: 16px;
        line-height: 20px;
        padding-left: 8px;
        font-weight: 600;
    }
    /*表格顶部的标题*/
    .right-content :deep(.ant3-col) {
        height: 50px;
    }
    tree-btns {
        display: flex;
        justify-content: space-around;
    }
    :deep(.ant3-tree-node-content-wrapper:hover) .svg-icon {
        display: inline-block;
    }
    .left-tree .search {
        margin-bottom: 16px;
    }
    .my-page :deep(.ant3-form-item-label) {
        width: 85px;
    }
    .svg-icon {
        display: none;
        outline: none;
    }
</style>
